package hu.myai.util.web;

import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * download a stock chart picture from BigCharts
 * */
public class DownloadBigChartsPic {

    /**
     * The object used when logging debug,errors,warnings and info.
     * */
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private DownloadURLNoCookies webNoCookies = new DownloadURLNoCookies();

    public boolean getPic(String prefix, String symbol, String posfix) {

        String myUrl = new String(
                        "http://bigcharts.marketwatch.com/charts/big.chart?symb=AU:"
                                        + symbol
                                        + "&ma=4&maval=9&uf=0&lf=256&lf2=128&lf3=268435456&type=4&size=2&style=320&time=5&freq=1&nosettings=1&mocktick=1");

        log.debug(myUrl);
        try {

                BufferedInputStream gifPic = new BufferedInputStream(webNoCookies.getURLGetString(new URL(myUrl)));

                // File gifFile = new
                // File("chart"+File.pathSeparator+symbol+".gif");

                FileOutputStream fos;
                DataOutputStream ds;

                File picFolder = new File(prefix);
                picFolder.mkdir();

                File picFile = new File(picFolder, symbol + "_" + posfix + ".gif");

                fos = new FileOutputStream(picFile);

                // Wrap the FileOutputStream with a
                // DataOutputStream to obtain its writeInt()
                // method.
                ds = new DataOutputStream(fos);

                byte buffer[] = new byte[4096];

                int bytesRead;

                while ((bytesRead = gifPic.read(buffer)) > 0) {
                        ds.write(buffer, 0, bytesRead);
                        ds.flush();
                }

                ds.close();

        } catch (Exception e) {
                e.printStackTrace();
                return false;
        }

        return true;
}

}
